<template>
  <div>
    <div style="margin-bottom: 20px">
      <!-- 查找 -->
      <el-space wrap>
        <!-- 请输入优惠券标题 -->
        <el-input class="logInput" placeholder="请输入优惠券标题" v-model="title" />
        <!-- 请输入优惠券标题 -->
        <el-select v-model="type" placeholder="请选择优惠券类型">
          <el-option
            v-for="item in optionType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- 用户性别选择 -->
        <el-select v-model="status" placeholder="请选择优惠券状态">
          <el-option
            v-for="item in optionStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="onSearch">
          <span class="iconfont icon-sousuo"></span>查找
        </el-button>
        <el-button type="primary" @click="addData">
          <span class="iconfont icon-tianjia"></span>添加
        </el-button>
        <el-button type="primary" @click="pageExport">
          <span class="iconfont icon-xiazaidangqianye"></span>当前页导出
        </el-button>
      </el-space>
    </div>
    <!-- 表格 -->
    <el-table ref="tableRef" border row-key="date" :data="tableData" style="width: 100%">
      <el-table-column
        prop="id"
        label="优惠券ID"
        align="center"
        sortable
        width="180"
        column-key="date"
      />
      <el-table-column prop="title" label="优惠券名称" align="center" />
      <el-table-column prop="type" label="优惠券类型" align="center">
        <template #default="scope">{{ scope.row.type == 1 ? "满减券" : "" }}</template>
      </el-table-column>
      <el-table-column prop="description" label="介绍" align="center"></el-table-column>
      <el-table-column prop="total" label="优惠券数量" align="center" />
      <el-table-column prop="surplus" label="剩余数量" align="center" />

      <el-table-column prop="limit" label="每人限领" align="center"></el-table-column>
      <el-table-column prop="discount" label="满减金额" align="center">
        <template #default="scope">减免{{ scope.row.discount}}元</template>
      </el-table-column>
      <el-table-column prop="min" label="最低消费" align="center">
        <template #default="scope">满{{ scope.row.min }}元可用</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag>{{ scope.row.status ? scope.row.gmtEnd > new Date().getTime() || scope.row.gmtEnd == null ? "正常" :'已过期': "下架" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryTitle" label="使用类目名称" align="center">
        <template #default="scope">
          <el-tag>{{ scope.row.categoryTitle ? scope.row.categoryTitle : "全部类目" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryId" label="使用类目ID" align="center" />
      <el-table-column prop="days" label="领券相对天数" align="center">
        <template #default="scope">{{ scope.row.days ? scope.row.days : "无" }}</template>
      </el-table-column>
      <el-table-column prop="gmtStart" label="领券开始时间" align="center">
        <template #default="scope">
          {{
          scope.row.gmtStart
          ? new Date(scope.row.gmtStart)
          .toLocaleDateString()
          .replace(/\//, "-")
          .replace(/\//, "-") +
          new Date(scope.row.gmtStart).toTimeString().substr(0, 8)
          : "无"
          }}
        </template>
      </el-table-column>

      <el-table-column prop="gmtEnd" label="领券结束时间" align="center">
        <template #default="scope">
          {{
          scope.row.gmtEnd
          ? new Date(scope.row.gmtEnd)
          .toLocaleDateString()
          .replace(/\//, "-")
          .replace(/\//, "-") +
          new Date(scope.row.gmtEnd).toTimeString().substr(0, 8)
          : "无"
          }}
        </template>
      </el-table-column>
      <el-table-column prop label="操作" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleActive(scope.$index)"
          >{{ scope.row.status == 0 ? "激活" : "冻结" }}</el-button>
          <el-button size="small" type="primary" @click="handleCheck(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogFormTitle">
      <el-form
        ref="ruleFormRef"
        :model="formData"
        label-position="left"
        label-width="auto"
        status-icon
        :rules="rules"
        show-message
        :disabled="dialogFormTitle=='编辑'"
      >
        <el-form-item prop="title" label="优惠券名称">
          <el-input style="width: 180px" v-model="formData.title" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择优惠券类型">
            <el-option
              v-for="item in optionType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍:" prop="description">
          <el-input style="width: 180px" v-model="formData.description" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券数量" prop="total" required>
          <el-input v-model="formData.total" placeholder="0">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="limit" required>
          <el-input v-model="formData.limit" placeholder="0">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discount" required>
          <el-input v-model="formData.discount" placeholder="0">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="min" required>
          <el-input v-model="formData.min" placeholder="0">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status" required>
          <el-select v-model="formData.status" placeholder="请选择优惠券状态">
            <el-option
              v-for="item in optionStatus"
              :label="item.label"
              :value="item.value"
              :key="item.value"
              v-show="item.label != '全部'"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="categoryId">
          <el-radio-group v-model="termOfValidity">
            <el-radio-button label="领券相对天数" />
            <el-radio-button label="指定绝对时间" />
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formData.days" v-if="termOfValidity == '领券相对天数'" placeholder="0">
            <template #append>天</template>
          </el-input>
          <div v-if="termOfValidity=='指定绝对时间'">
             <el-config-provider :locale="locale">
            <el-date-picker
              v-model="formData.gmtStart"
              type="datetime"
              placeholder="选择日期"
              format="YYYY/MM/DD hh:mm"
              value-format="x"
            />至
            <el-date-picker
              v-model="formData.gmtEnd"
              type="datetime"
              placeholder="选择日期"
              format="YYYY/MM/DD hh:mm"
              value-format="x"
            />
           </el-config-provider>
          </div>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <el-radio-group v-model="limitScope">
            <el-radio-button label="全场通用" name="type" />
            <el-radio-button label="指定分类" name="type" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠类目" prop="categoryId" v-if="limitScope=='指定分类'">
          <el-cascader
            v-model="formData.categoryId"
            :options="options"
            :props="props"
            :show-all-levels="false"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="Cancel">取消</el-button>
          <el-button type="primary" v-if="createShow" @click="onSubmit(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- //分页 -->
    <daily-demo v-bind="demo" @pages="pages" @limits="limits"></daily-demo>
  </div>
</template>

<script>
import http from "@/util/http";
import DailyDemo from "@/components/DailyOperation/Demo.vue";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
// 做当前页导出时所需要的引入
import FileSaver from "file-saver";
import { utils, write } from "xlsx";
export default {
  components: {
    DailyDemo,
    ElConfigProvider//国际化中文
  },

  data() {
    var integ =[
           {
            trigger: "blur",
            required: true,
            message: "请输入整数",
            pattern: /^[0-9a-zA-Z\u4e00-\u9fa5]{1,10}$/,
          },
    ]
    return {
      locale: zhCn,//国际化中文
      createShow: false,
      limitScope: "全场通用", //商品限制范围
      termOfValidity: "领券相对天数", //有效期
      // 领券相对天数
      days: false,
      times: false,
      // 弹框标题
      dialogFormTitle: "",
      // 弹框隐藏
      dialogFormVisible: false,
      // 弹框的数据
      formData: {
        title: "", //优惠券名称
        type: "", //优惠券类型
        description: "", //介绍
        total: 1, //优惠券数量
        limit: 1, //每人限领
        discount: 1, //满减金额
        min: 1, //最低消费
        status: "", //状态
        categoryId: "", //有效期--优惠类别
        days: "", //天数
        gmtStart: "", //领券开始时间
        gmtEnd: "", //领券结束时间
        categoryTitle: "", //优惠券类目名称
      },
      // 类目树list
      options: [],
      // 类目树配置选项
      props: {
        checkStrictly: true,
        label: "title",
        value: "id",
        children: "childrenList",
        emitPath: false,
      },

      // 规则
      rules: {
        title: [
          {
            trigger: "blur",
            required: true,
            message: "优惠券标题不能为空",
          },
        ],
        type: [
          {
            trigger: "blur",
            required: true,
            message: " ",
          },
        ],
        total: [
           {
            trigger: "blur",
            required: true,
            message: "请输入优惠券数量",

          },
         ...integ
        ],
        limit: [
           {
            trigger: "blur",
            required: true,
            message: "请输入每人限量",

          },
          ...integ
        ],
        discount: [
           {
            trigger: "blur",
            required: true,
            message: "请输入优惠金额",

          },
          ...integ
        ],
        min: [
           {
            trigger: "blur",
            required: true,
            message: "请输入最低金额",

          },
          ...integ
        ],
        categoryTitle: [
          {
            trigger: "blur",
            required: true,
          },
        ],

      },
      // 优惠券列表数据
      tableData: [],
      // 分页数据
      demo: {
        page: 1,
        limit: 10,
        total: 1, //分页--总条数
      },
      // 状态选择
      optionStatus: [
        { label: "下架", value: 0 },
        { label: "正常", value: 1 },
        { label: "全部", value: " " },
      ],
      // 优惠券类型
      optionType: [
        { label: "全部", value: 0 },
        { label: "满减券", value: 1 },
      ],
      // 查询的信息
      title: "",
      type: "",
      status: "",
    };
  },
  created() {
    this.couponMem();
  },
  methods: {
    // 导出当前页
    pageExport() {
      var wb = utils.table_to_book(document.querySelector(".el-table"));
      var wbout = write(wb, { bookType: "xlsx", bookSST: true, type: "array" });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "优惠券表格导出.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    // 查看
    handleCheck(row) {
      this.treeList();
      this.dialogFormTitle = "编辑";
      Object.assign(this.formData, row); //把row赋值给 this.formUser
      this.createShow = false;
      this.dialogFormVisible = true;

      if (row.categoryId) {
        this.limitScope = "指定分类";
      } else {
        this.limitScope = "全场通用";
      }

      if (row.gmtStart && row.gmtEnd) {
       this.termOfValidity = '指定绝对时间'
      }else if(row.days){
       this.termOfValidity = '领券相对天数'

      }

    },
    // 激活
    handleActive(index) {
      if (this.tableData[index].status == 0) {
        this.tableData[index].status = 1;
        ElMessage.success("激活成功");
        return;
      }
      if (this.tableData[index].status == 1) {
        this.tableData[index].status = 0;
        ElMessage.success("冻结成功");

        return;
      }
    },
    // 取消弹框
    Cancel() {
      this.dialogFormVisible = false;
      this.couponMem();
    },
    // 点击弹框确定
    onSubmit(ruleFormRef) {
         console.log(123,"点击弹框确定");
        if (!ruleFormRef){
            return ElMessage.success("表单验证失败");
        }

      this.$ref[ruleFormRef].validate((valid, fields) => {
        console.log(123,"表单验证");

    if (valid) {
        console.log(123,"表单验证成功");

      console.log('submit!')
       let Data = {
        _gp: "admin.coupon",
        _mt: "create",
        ...this.formData,
      };
      http.post(Data).then((res) => {
        if (200 == res.data.errno) {
          ElMessage.success("创建成功");

          this.couponMem();
        }
      });
      this.dialogFormVisible = false;
    } else {
      console.log('error submit!', fields)
    }
  })


    },
    // 添加
    addData() {
      this.treeList();
      this.formData.title = "";
      this.formData.type = "";
      this.formData.description = "";
      this.formData.total = 1;
      this.formData.limit = 1;
      this.formData.discount = 1;
      this.formData.min = 1;
      this.formData.categoryId = "";
      this.formData.status = "";
      this.formData.categoryTitle = "";
      this.formData.days = "";
      this.formData.gmtStart = "";
      this.formData.gmtEnd = "",

      this.dialogFormTitle = "创建";
      this.dialogFormVisible = true;
      this.createShow = true;
    },
  // 类目树请求
    treeList() {
      let treeData = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      http.post(treeData).then((res) => {
        this.options = res.data.data;
        this.couponMem();
      });
    },
    // 查找
    onSearch() {
      this.couponMem();
    },
    // 优惠券数据请求
    couponMem() {
      let userData = {
        _gp: "admin.coupon",
        _mt: "list",
        pageNo: this.demo.page,
        limit: this.demo.limit,
        title: this.title,
        type: this.type,
        status: this.status,
      };
      http.post(userData).then((res) => {
        console.log(res, "渲染成功");
        this.tableData = res.data.data.items;
        this.demo.total = res.data.data.total;
      });
    }, //分页---当前页数
    pages(e) {
      console.log(e, 456);
      this.demo.page = e;
      this.couponMem();
    },
    // 分页---每页显示条目个数
    limits(e) {
      this.demo.limit = e;
      this.couponMem();
    },
  },
};
</script>
